package main

import (
	"fmt"
	"github.com/go-redis/redis"
	"regexp"
	"strconv"
	"strings"
)

func main() {
	var rdb *redis.Client

	rdb = redis.NewClient(&redis.Options{
		Addr: "localhost:6379",
	})
	if _, err := rdb.Ping().Result(); err != nil {
		fmt.Println(err)
		return
	}
	beforeUsedMem := getUsedMemory(rdb)
	fmt.Printf("current memory is %d\n", beforeUsedMem)
	fmt.Println("connect successful")
	for i := 0; i < 50; i++ {
		rv := strings.Repeat("t", (i+1)*10000)
		rk := "test" + strconv.Itoa(i)
		addBeforeUsedMem := getUsedMemory(rdb)
		err := rdb.Set(rk, rv, 0).Err()
		if err != nil {
			fmt.Println(err)
			continue
		}
		addAfterUsedMem := getUsedMemory(rdb)
		fmt.Printf("key %s: size is %d byte. memory used %d.\n", rk, len(rv), addAfterUsedMem-addBeforeUsedMem)
	}
}

func getUsedMemory(rdb *redis.Client) int {
	usedMemStr := rdb.Info("memory").Val()
	r, _ := regexp.Compile("used_memory:(\\d+)")
	usedMemMatch := r.FindStringSubmatch(usedMemStr)
	usedMem, _ := strconv.Atoi(usedMemMatch[1]) //uint8
	return usedMem
}
